package com.sahyadri.web.util.tags;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * Convenience tag used to make the base URL of the current request available as a JSP REQUEST scoped attribute.
 * Builds base URL in the form schema://serverName[:port]. <br />
 * Port number is only included if a port other the default port (80) is specified.
 * Makes the value available under the key specified by the {@link #var} attribute.  Defaults to 'baseURL' if non specified. 
 *
 */
public class BaseUrlTag extends SimpleTagSupport {

	private Logger log = Logger.getLogger(getClass());
	
	private static final String DEFAULT_VAR_NAME = "baseURL";
	private String var = DEFAULT_VAR_NAME;
	
	private static int DEFAULT_PORT = 80;
	private static final String PORT_SEPERATOR = ":";
	private static final String SCHEME_SERVER_SEPERATOR = "://";
	
	/**
	 * Constructs baseUrl and adds it to the Request scope under the key specified by the var attribute.
	 */
	public void doTag() throws JspException, IOException {
		
		String baseUrl = buildBaseUrl();
		
		getJspContext().setAttribute(var, baseUrl, PageContext.REQUEST_SCOPE);
		
	}
	
	/**
	 * Private Utility method used to build the base URL
	 * @return String representing the base URL in the form: <br />
	 * scheme://serverName[:port] if non standard port is specified.
	 */
	private String buildBaseUrl() {
		
		HttpServletRequest req = (HttpServletRequest)((PageContext)getJspContext()).getRequest();
		
		StringBuilder sb = new StringBuilder();
		sb.append(req.getScheme()).append(SCHEME_SERVER_SEPERATOR).append(req.getServerName());
		
		// Only add explicit port number for non standard port (80)
		int port = req.getServerPort();
		if (port != DEFAULT_PORT) {
			sb.append(PORT_SEPERATOR).append(port);
		}
		
		log.debug("Built baseUrl of " + sb.toString() + " from raw URL of " + req.getRequestURL());
		return sb.toString();
	}
	
	public String getVar() {
		return this.var;
	}

	public void setVar(String var) {
		this.var = (StringUtils.isNotBlank(var)) ? var : DEFAULT_VAR_NAME;
	}

	
}